package com.yabushan.form.service.impl;

import java.util.Date;
import java.util.List;

import com.yabushan.common.utils.DateUtils;
import com.yabushan.common.utils.SecurityUtils;
import com.yabushan.common.utils.StringUtils;
import com.yabushan.form.domain.*;
import com.yabushan.form.mapper.FormInfosMapper;
import com.yabushan.form.service.IAutoTableFiledsService;
import com.yabushan.form.service.IAutoUserTablesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yabushan.form.mapper.AutoUserTableMapper;
import com.yabushan.form.service.IAutoUserTableService;

/**
 *  动态表信息Service业务层处理
 *
 * @author yabushan
 * @date 2021-08-06
 */
@Service
public class AutoUserTableServiceImpl implements IAutoUserTableService
{
    @Autowired
    private AutoUserTableMapper autoUserTableMapper;
    @Autowired
    private IAutoUserTablesService IAutoUserTablesServiceService;

    @Autowired
    private FormInfosMapper formInfosMapper;

    @Autowired
    private IAutoTableFiledsService filedsService;


    /**
     * 查询 动态表信息
     *
     * @param bId  动态表信息ID
     * @return  动态表信息
     */
    @Override
    public AutoUserTable selectAutoUserTableById(String bId)
    {
        return autoUserTableMapper.selectAutoUserTableById(bId);
    }

    /**
     * 查询 动态表信息列表
     *
     * @param autoUserTable  动态表信息
     * @return  动态表信息
     */
    @Override
    public List<AutoUserTable> selectAutoUserTableList(AutoUserTable autoUserTable)
    {
        return autoUserTableMapper.selectAutoUserTableList(autoUserTable);
    }

    @Override
    public int insertAutoUserTable(AutoUserTable autoUserTable)
    {
        AutoUserTables tables = new AutoUserTables();
        tables.setuId(SecurityUtils.getLoginUser().getUser().getUserId());
        AutoUserTables autoUserTables1 = new AutoUserTables();
        List<AutoUserTables> autoUserTables = IAutoUserTablesServiceService.selectAutoUserTablesList(tables);
        if(autoUserTables.size()==0){
            //创建用户VIP等级1，默认初始化创建5张表
            autoUserTables1.setAllowTableNum(Long.valueOf(5));
            autoUserTables1.setVipLevel("南瓜籽");
            autoUserTables1.setCreatedBy(SecurityUtils.getUsername());
            autoUserTables1.setCreatedTime(DateUtils.getNowDate());
            autoUserTables1.setuId(SecurityUtils.getLoginUser().getUser().getUserId());
            IAutoUserTablesServiceService.insertAutoUserTables(autoUserTables1);
        }else{
            autoUserTables1=autoUserTables.get(0);
            //判断是否超过最大建表数量
            AutoUserTable autoUserTablev = new AutoUserTable();
            autoUserTablev.setCreatedBy(SecurityUtils.getUsername());
            int size = autoUserTableMapper.selectAutoUserTableList(autoUserTablev).size();
            //判断用户等级是否允许再创建表
            if(autoUserTables1.getVipLevel().equals("南瓜籽")){
                if(size>= Constant.NGZ.getCREATE_TABLE_NUM()){
                    return 100;//超过最大建表数
                }
            }else if(autoUserTables1.getVipLevel().equals("南瓜苗")){
                if(size>= Constant.NGM.getCREATE_TABLE_NUM()){
                    return 100;//超过最大建表数
                }
            }else if (autoUserTables1.getVipLevel().equals("南瓜藤")){
                if(size>= Constant.NGT.getCREATE_TABLE_NUM()){
                    return 100;//超过最大建表数
                }
            }else if(autoUserTables1.getVipLevel().equals("南瓜花")){
                if(size>= Constant.NGH.getCREATE_TABLE_NUM()){
                    return 100;//超过最大建表数
                }
            }else if(autoUserTables1.getVipLevel().equals("南瓜树")){
                if(size>= Constant.NGS.getCREATE_TABLE_NUM()){
                    return 100;//超过最大建表数
                }
            }else{
                return 100;//超过最大建表数
            }
        }

        //封装建表英文名等信息
        autoUserTable.setbId(StringUtils.getUUID());
        autoUserTable.setCreatedBy(SecurityUtils.getUsername());
        autoUserTable.setCreatedTime(DateUtils.getNowDate());
        autoUserTable.setuId(SecurityUtils.getLoginUser().getUser().getUserId());
        autoUserTable.setbEnName(SecurityUtils.getUsername()+"_"+DateUtils.dateTimeNow());
        //创建表
        StringBuffer createTable = new StringBuffer();
        createTable.append("create table ").append(autoUserTable.getbEnName())
                .append(" (")
                .append("T_ID INT NOT NULL AUTO_INCREMENT  COMMENT '乐观锁', PRIMARY KEY (T_ID) ")
                .append(")");
        formInfosMapper.dynamicsCreate(createTable.toString());

        return autoUserTableMapper.insertAutoUserTable(autoUserTable);
    }

    /**
     * 修改 动态表信息
     *
     * @param autoUserTable  动态表信息
     * @return 结果
     */
    @Override
    public int updateAutoUserTable(AutoUserTable autoUserTable)
    {
        autoUserTable.setUpdatedBy(SecurityUtils.getUsername());
        autoUserTable.setUpdatedTime(DateUtils.getNowDate());
        return autoUserTableMapper.updateAutoUserTable(autoUserTable);
    }

    /**
     * 批量删除 动态表信息
     *
     * @param bIds 需要删除的 动态表信息ID
     * @return 结果
     */
    @Override
    public int deleteAutoUserTableByIds(String[] bIds)
    {
        return autoUserTableMapper.deleteAutoUserTableByIds(bIds);
    }

    /**
     * 删除 动态表信息信息
     *
     * @param bId  动态表信息ID
     * @return 结果
     */
    @Override
    public int deleteAutoUserTableById(String bId)
    {
        return autoUserTableMapper.deleteAutoUserTableById(bId);
    }

    @Override
    public int addFiledValue(FiledInsertInfo filedInsertInfo) {
        StringBuffer buffer = new StringBuffer();
        //识别字段类型
        AutoTableFileds fileds = new AutoTableFileds();
        AutoTableFileds fileds1 = filedsService.selectAutoTableFiledsById(filedInsertInfo.getFiledId());

        //判断是新增还是更新
        if(filedInsertInfo.getKeyId()==null || filedInsertInfo.getKeyId()!=0){
            //插入
            buffer.append("insert into ").append(filedInsertInfo.getTableName()).append("(")
                    .append(filedInsertInfo.getFiledName()).append(") values(");

            insertInfo(filedInsertInfo, buffer, fileds1);
            buffer.append(")");

        }else{
            //更新
            buffer.append("update ").append(filedInsertInfo.getTableName()).append(" set ")
                    .append(filedInsertInfo.getFiledName()).append("=");

            insertInfo(filedInsertInfo, buffer, fileds1);


        }
        formInfosMapper.dynamicsInsert(buffer.toString());
        return 1;
    }

    private void insertInfo(FiledInsertInfo filedInsertInfo, StringBuffer buffer, AutoTableFileds fileds1) {
        if(fileds1.getFiledType().contains("varchar") || fileds1.getFiledType().contains("text") ||fileds1.getFiledType().contains("date")){
            //字符串
            buffer.append("'").append(filedInsertInfo.getFiledValue()).append("'");
        }
//        else if(fileds1.getFiledType().contains("date")){
//            //日期
//            Date date = DateUtils.dateTime("yyyy-MM-dd", filedInsertInfo.getFiledValue());
//            buffer.append(date);
//        }else if(fileds1.getFiledType().contains("datetime")){
//            //日期时间
//            Date date = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", filedInsertInfo.getFiledValue());
//            buffer.append(date);
//        }
        else{
            //数值
            buffer.append(filedInsertInfo.getFiledValue());
        }
    }
}
